<template>
  <div>
    <Form ref="form" :model="formItem" :rules="formItemRules" :label-width="100">
      <FormItem label="角色编码" prop="roleCode">
        <Input v-model="formItem.roleCode" placeholder="请输入内容"></Input>
      </FormItem>
      <FormItem label="角色名称" prop="roleName" :rules="$rules.required('角色名称不能为空')">
        <Input v-model="formItem.roleName" placeholder="请输入内容"></Input>
      </FormItem>
      <FormItem label="状态">
        <RadioGroup v-model="formItem.status" type="button">
          <Radio :label="0">禁用</Radio>
          <Radio :label="1">正常</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="描述">
        <Input v-model="formItem.roleDesc" type="textarea" placeholder="请输入内容"></Input>
      </FormItem>
    </Form>
  </div>
</template>

<script>
export default {
  name: 'RoleInfo',
  data () {
    const validateEn = (rule, value, callback) => {
      const reg = /^[_a-zA-Z0-9]+$/
      if (value === '') {
        callback(new Error('角色编码不能为空'))
      } else if (value !== '' && !reg.test(value)) {
        callback(new Error('只允许字母、数字、下划线'))
      } else {
        callback()
      }
    }
    return {
      isAdd: true,
      formItemRules: {
        roleCode: [
          { required: true, validator: validateEn, trigger: 'blur' }
        ]
      },
      formItem: this.getFormItem()
    }
  },
  methods: {
    getFormItem () {
      return {
        roleId: '',
        roleCode: '',
        roleName: '',
        status: 1,
        roleDesc: ''
      }
    },
    setData (data) {
      this.isAdd = true
      if (data && data.roleId) {
        Object.assign(this.formItem, {
          roleId: data.roleId,
          roleCode: data.roleCode,
          roleName: data.roleName,
          status: data.status,
          roleDesc: data.roleDesc
        })
        this.isAdd = false
      } else {
        this.formItem = this.getFormItem()
        this.$refs['form'].resetFields()
      }
    },
    handleReset () {
      this.$refs['form'].resetFields()
      this.formItem = this.getFormItem()
    },
    handleSubmit () {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.$http.post(this.$apis.role.save, this.formItem, this).then(res => {
              resolve(res)
            }).catch(function (err) {
              reject(err)
            })
          } else {
            resolve(false)
          }
        })
      })
    }
  },
  mounted: function () {
  }
}
</script>
